from rest_framework import serializers

from booktest.models import BookInfo


class BookInfoModelSerializer(serializers.ModelSerializer):
    """图书数据序列化器"""
    class Meta:
        # model:指明该序列化器处理的数据字段从模型类BookInfo参考生成
        # fields:指明该序列化器包含模型类中的哪些字段，
        # '__all__':指明包含所有字段
        model = BookInfo  # 给序列化器指定要映射的模型
        # fields = '__all__'  # 映射模型中所有字段到序列化器中
        # fields = ['id', 'btitle', 'bpub_date'] #表示指定映射哪些字段
        exclude = ['image'] # 排除指定字段，其它都要
        # 给某些字段额外修改或追加字段选项
        extra_kwargs = {
            'bread':{'min_value':0, 'required':True},
            'bcomment': {'min_value':0, 'required':True},
        }
        # 让某些字段在序列化时，是只读的（只能进行序列化，不能进行反序列化）
        read_only_fields = ('id', 'bread', 'bcomment')









class BookInfoSerializer(serializers.Serializer):
    """图书数据序列化器"""
    id = serializers.IntegerField(label='ID', read_only=True)
    btitle = serializers.CharField(label='名称', max_length=20)
    bpub_date = serializers.DateField(label='发布日期', required=False)
    bread = serializers.IntegerField(label='阅读量', required=False)
    bcomment = serializers.IntegerField(label='评论量', required=False)
    image = serializers.ImageField(label='图片', required=False),
    #　many=True是告诉序列化器次字段有多个数据
    heroinfo_set = serializers.StringRelatedField(read_only=True, many=True)

    # def validate_btitle(self,value):  # 方法格式： validate_字段名字（）
    #     """给单个字段额外追加校验逻辑"""
    #     if 'django' not in value.lower():
    #         raise serializers.ValidationError("图书不是关于Django的")
    #     return value
    #
    # def validate(self, attrs):
    #     """多个字段之间进行校验用此方法"""
    #     bread = attrs['bread']
    #     bcomment = attrs['bcomment']
    #     if bread < bcomment:
    #         raise serializers.ValidationError('阅读量小于评论量')
    #     return attrs

    def create(self, validated_data):
        """新建"""
        return BookInfo.objects.create(**validated_data)

    def update(self, instance, validated_data):
        # super(BookInfoSerializer, self).update()
        """更新，instance为要更新的对象实例"""
        instance.btitle = validated_data.get('btitle', instance.btitle)
        instance.bpub_date = validated_data.get('bpub_date', instance.bpub_date)
        instance.bread = validated_data.get('bread', instance.bread)
        instance.bcomment = validated_data.get('bcomment', instance.bcomment)
        instance.save()
        return instance


class HeroInfoSerializer(serializers.Serializer):
    """英雄数据序列化器"""
    GENDER_CHOICES = (
        (0, 'male'),
        (1, 'female')
    )
    id = serializers.IntegerField(label='ID', read_only=True)
    hname = serializers.CharField(label='名字', max_length=20)
    hgender = serializers.ChoiceField(choices=GENDER_CHOICES, label='性别', required=False)  # 返回关联模型的id值
    hcomment = serializers.CharField(label='描述信息', max_length=200, required=False, allow_null=True)
    hbook = serializers.StringRelatedField(label='图书', read_only=True)  # 会拿到关联的模型ｓｔｒ方法返回值
    hbook = BookInfoModelSerializer()  # 此方法会把关联序列化器中的所有数据拿到